﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;
using Microsoft.Win32;
using MostRecentlyUsed.Models.EventArguments;

namespace TestApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var connectionStrings = Application.UserAppDataRegistry.GetValue("ConnectionStrings", null);

            if(connectionStrings != null)
            {
                databaseConnections1.SetEncryptedConnectionStrings(connectionStrings.ToString());
            }
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataConnectionDialog dcd = new DataConnectionDialog();
            DataSource.AddStandardDataSources(dcd);

            if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
            {
                databaseConnections1.AddItem(dcd.ConnectionString, dcd.SelectedDataProvider.Name);
            }
        }

        private void databaseConnections1_ItemSelectedEvent(object sender, SelectedConnectionString e)
        {
            var provider = DbProviderFactories.GetFactory(e.Provider);
            var connection = provider.CreateConnection();
            connection.ConnectionString = e.ConnectionString;
            connection.Open();
            MessageBox.Show(this, "Opened connection: " + e.DisplayName);
        }

        private void toolStripButtonGetStrings_Click(object sender, EventArgs e)
        {
            textBoxCStrings.Text = databaseConnections1.GetEncryptedConnectionStrings();
        }

        private void toolStripButtonSetStrings_Click(object sender, EventArgs e)
        {
            databaseConnections1.SetEncryptedConnectionStrings(textBoxCStrings.Text);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.UserAppDataRegistry.SetValue("ConnectionStrings", databaseConnections1.GetEncryptedConnectionStrings());
        }
    }
}
